package com.example.zjx8969.myapplication;


import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.FutureTarget;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Calendar;
import java.util.Enumeration;

import hawk.sit.threads.PriorityThreadPool;

//@Route(path = "/transform/java")
public class TranstraintActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String avatarUrl = "https://avatar-static.segmentfault.com/394/665/3946658505-57354a8342e30_huge256";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.constrain_layout_demo);

        findViewById(R.id.tag_transition_group).setOnClickListener(this);
        findViewById(R.id.btn_c).setOnClickListener(this);
        findViewById(R.id.btn_b).setOnClickListener(this);

        int PERMISSION_ALL = 1;
        String[] PERMISSIONS = {
                Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
        };
        /*IosLoadingView loadingView = findViewById(R.id.isLoadingView);
        getLifecycle().addObserver(loadingView);*/

    }


    @Override
    protected void onStart() {
        super.onStart();
/*      EditText editText =  findViewById(R.id.verify_email_code_email_code);
      editText.requestFocus();*/
    }

    private boolean hasPermissions(Context context, String[] permissions) {
        for (String p : permissions) {
            if (ActivityCompat.checkSelfPermission(context, p) == PackageManager.PERMISSION_DENIED)
                return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_b:
//                surfaceView.startPlayWithThumb(getLifecycle(), "introduce/introduce_1.mp4", mediaPlayer);
/*                Intent intent = new Intent(this, MainActivity.class);//,sign_in_password_hint,sign_in_password_hint
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                showNotification(this, defaultChannelId, "notificationtTitle",
                        "notificationContent", pendingIntent, avatarUrl);*/
                Log.d("tag", getMacAddress());
                break;
            case R.id.tag_transition_group:
            case R.id.btn_c:
//                startActivity(new Intent(this, OnBoardingActivity.class));
//                ImageView imageView = findViewById(R.id.image);
//                Glide.with(imageView).load("file:///android_asset/" + "hair_avatar.png").diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
                break;
        }
    }

    public void showNotification(final Context context, final String channelId, final String title, final String content,
                                 final PendingIntent pendingIntent, final String avatarUrl) {
        final int notificationId = getNotificationId(title, content);
        if (TextUtils.isEmpty(avatarUrl)) {
            showNotification(context, channelId, title, content, null, pendingIntent, notificationId);
            return;
        }
        PriorityThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                int px = dip2px(context, 64);
                FutureTarget<Bitmap> submit = Glide.with(TranstraintActivity.this).asBitmap().transform(new CircleCrop()).load(avatarUrl).submit(px, px);
                Bitmap bitmap = null;
                try {
                    bitmap = submit.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showNotification(context, channelId, title, content, bitmap, pendingIntent, notificationId);
            }
        });

    }

    public int getNotificationId(String... args) {
        if (args == null || args.length == 0) return -1;
        int hash = 0;
        for (String parameter : args) {
            hash = hash * 31 + (TextUtils.isEmpty(parameter) ? 0 : parameter.hashCode());
        }
        return hash;
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void showNotification(Context context, String channelId, String title, String content, Bitmap bitmap,
                                 PendingIntent pendingIntent, int notificationId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            initChannels(context, defaultChannelId, defaultChannelName);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
        if (bitmap != null) {
            builder.addAction(new NotificationCompat.Action(null, "OPen Door", pendingIntent));
        }
        NotificationCompat.Style style = null;
        if (bitmap != null) {
            style = new NotificationCompat.BigPictureStyle().bigPicture(bitmap).bigLargeIcon(null);
            /* builder.setContentText(content).setStyle(bigPictureStyle);*/
        } else {
            style = new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(content);
        }
        builder.setContentTitle(title).setContentText(content)
                .setWhen(System.currentTimeMillis())
                .setLargeIcon(bitmap)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setColor(0xff9583fb).setStyle(style);


        boolean isShowSound = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) < 20
                && Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 8;

        if (isShowSound) {
            builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
        }
        NotificationManagerCompat.from(context).notify(notificationId, builder.build());
/*        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(notificationId, builder.build());*/
    }

    private static final String defaultChannelId = "1";
    private static final String defaultChannelName = "channel_default";
    private static final String serviceChannelName = "service_channel";

    private void initChannels(Context context, String channelId, String channelName) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return;
        }
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel2 = new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_HIGH);
        channel2.enableLights(true);
        channel2.setLockscreenVisibility(Notification.VISIBILITY_SECRET);//设置在锁屏界面上显示这条通知
        channel2.setLightColor(Color.GREEN);
        notificationManager.createNotificationChannel(channel2);

        NotificationChannel silentChannel = new NotificationChannel(serviceChannelName, serviceChannelName, NotificationManager.IMPORTANCE_DEFAULT);
        silentChannel.setLightColor(Color.GREEN);
        silentChannel.enableVibration(false);
        silentChannel.enableLights(false);
        notificationManager.createNotificationChannel(silentChannel);
    }

    private String getMacAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (networkInterface.getName().equalsIgnoreCase("wlan0")) {
                    continue;
                }
                byte[] hardwareAddress = networkInterface.getHardwareAddress();
                if (hardwareAddress == null) {
                    return "";
                }
                StringBuilder stringBuilder = new StringBuilder();
                for (byte b : hardwareAddress) {
                    stringBuilder.append(String.format("%02X:", b));
                }
                if (stringBuilder.length() > 0)
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                return stringBuilder.toString();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
